<?php
namespace app\api\service;

use app\Response;
use app\common\model\Parameter;
use app\common\service\CommonUserBlackService;
use app\common\model\User;
use app\common\model\Bank;
use app\common\model\Withdrawal;
use app\common\model\UserAmount;
use app\common\model\Detailed;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;

class UserWithdrawalService
{
    /*** 提现页面数据获取
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function withdrawalViewService($user_id){
        $User = User::userInfo(["uid"=>$user_id]);
        if(empty($User)){
            return Response::wrapError(0,"非法请求",-200);
        }
        if($User['type'] != 23){
            return Response::wrapError(0,"账户非达人会员",-200);
        }
        if($User['enable'] == 0){
            return Response::wrapError(0,"此账户已被禁用",-200);
        }

        $userAmount = UserAmount::userAmountInfo(['uid'=>$user_id]);
        $info = [];
        $info['balance'] = $userAmount['balance']; //余额
        $info['reward_amount'] = $userAmount['reward_amount']; //赏金余额余额

        if(empty($User["pay_password"])){
            $info["is_set_pwd"] = 0;
        }else{
            $info["is_set_pwd"] = 1;
        }
        //提现费率计算

        $info['balance_rate'] = Parameter::parameterValue(["id"=>1]);//余额提现费率
//        $info['reward_rate'] = Parameter::parameterValue(["id"=>2]);//赏金/佣金提现费率
//        $info['invitation_rate'] = Parameter::parameterValue(["id"=>3]);//邀请奖励提现费率
        //银行卡
        $bank = Bank::bankList(['uid'=>$user_id,'enable'=>1],1,2);
        $info['bank'] = [];
        foreach ($bank as $item){
            $b = [];
            $b['id'] = $item['id'];
            $b['type'] = $item['type'];
            $b['bank_name'] = $item['bank_name'];
            $b['balance'] = $item['balance'];
            $b['bank_card'] = self::bankCardEdit($item['bank_type'],$item['bank_card']);
            $b['account_holder'] = self::alipayUsername($item['account_holder']);
            $info['bank'][] = $b;
        }

        return Response::wrapData($info);
    }




    /*** 提现
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function withdrawalService($user_id,$data){
        //防重复
        $file_name = Config::get("app.concurrency_fiel_path")."uploads/UserWithdrawalService/withdrawalService_".$user_id.".txt";
        $fz = file_exists($file_name);
        $buffer = 0;
        $str = time();
        $time = $str;
        if($fz){
            $fp=fopen($file_name,'r');
            while(!feof($fp))
            {
                $buffer=fgets($fp,4096);
            }

            fclose($fp);
        }
        $buffer=$buffer + 20;
        if($buffer  > $time){
            return Response::wrapError(0,'操作频繁,请20秒后再试!');
        }

        $file_pointer = fopen($file_name,"w+");
        fwrite($file_pointer,$str);
        fclose($file_pointer);


        if(Cache::has("userAmount".$user_id)&&!empty(Cache::get("userAmount".$user_id))&&Cache::get("userAmount".$user_id)>15){
            return Response::wrapError(0,'系统结算中请稍后再试!');
        }



        //交易密码判断
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(empty($userInfo['pay_password'])){
            return Response::wrapError(0,'您还未设置交易密码,请先去设置交易密码!');
        }else{
            if($userInfo['pay_password'] != \app\common\model\User::encPassword($data['payPassword'],$userInfo['encryption'])){
                return Response::wrapError(0,'交易密码不正确!');
            }
        }
        //提现禁用规则判断
        if($userInfo['wit_pro'] == 2){
            return Response::wrapError(0,'因账号违规操作，提现功能暂时被禁用，有问题联系客服!');
        }
        //银行绑定判断
        $userBank =  Bank::bankInfo(['id'=>$data['bankId'],'uid'=>$user_id,'enable'=>1]);
        if(empty($userBank)){
            return Response::wrapError(0,'提现卡片或支付宝账号不存在!');
        }
        //余额判断
        $UserAmount = UserAmount::userAmountInfo(['uid'=>$user_id]);//获取用户可用余额
        if(floatval($UserAmount['balance']) < floatval($data['money'])){
            return Response::wrapError(0,'可用余额不足!');
        }
        //提现只能一笔进行提现限制
        $userWithdrawal = Withdrawal::withdrawalView([['uid','=',$user_id],['type','=',1],['state','in','0,1']]);
        if(!empty($userWithdrawal)){
            return Response::wrapError(0,'当前已有一笔进行中的提现!');
        }
        $feilv = Parameter::parameterValue(["id"=>5]);
        if($feilv > 0){
            $fee = bcdiv($data['money'] * $feilv , 100,2); //用户端提现 费用
        }else{
            $fee = 0; //用户端提现 费用
        }

        $to_account = bcsub($data['money'],$fee,2);
        $no_order = 'W'.date('YmdHis',time()). rand(10000,99999);
        //提现数据记录
        $withdrawal = [
            'uid' => $user_id,
            'no_order' => $no_order,
            'withdrawal' => $data['money'],
            'fee' => $fee,
            'to_account' => $to_account,
            'transfer_bank' => $userBank['bank_name'],
            'transfer_card' => $userBank['bank_card'],
            'transfer_name' => $userBank['account_holder'],
            'addtime' => time()
        ];
        $withdrawalId = Withdrawal::withdrawalAdd($withdrawal)['id'];
        Cache::set("userAmount".$user_id,20,20);
        Db::startTrans();//开启事务
            //资金流水记录
            $detailed = \detailed($user_id,$data['money'],'withdrawal_freeze',$UserAmount['balance'],$withdrawalId,'',$no_order);
            Detailed::detailedAdd($detailed);
            //用户资金扣除  转冻结
            UserAmount::userAmountInc(["uid"=>$user_id,"id"=>$UserAmount["id"]],"freezing_amount",floatval($data['money']));
            UserAmount::userAmountDec(["uid"=>$user_id,"id"=>$UserAmount["id"]],"balance",floatval($data['money']));
            Cache::delete("userAmount".$user_id);
        Db::commit();//事务提交


//        //提现黑号判断-暂无
//        CommonUserBlackService::userBlack($withdrawalId,$user_id);

        $res = ['to_account'=>$to_account,'fee'=>$fee];
        return Response::wrapData($res);
    }




    /*** 提现限制条件获取
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function withdrawalStateService($user_id){
        $User = User::userInfo(["uid"=>$user_id]);
        if(empty($User)){
            return Response::wrapError(0,"非法请求",-200);
        }
        if($User['type'] != 23){
            return Response::wrapError(0,"账户非达人会员",-200);
        }
        if($User['enable'] == 0){
            return Response::wrapError(0,"此账户已被禁用",-200);
        }

        //提现只能一笔进行提现限制
        $userWithdrawal = Withdrawal::withdrawalView([['uid','=',$user_id],['type','=',1],['state','in','0,1']]);
        if(!empty($userWithdrawal)){
            return Response::wrapError(0,"当前已有一笔进行中的提现");
        }
        return Response::wrapData();
    }




    public static function withdrawalDataService($user_id,$page,$num){
        $where[] = ["uid","=",$user_id];
        $where[] = ["type","in","withdrawal_freeze,withdrawal_fee,withdrawal_success,withdrawal_unfreeze"];
        $list = Detailed::detailedList($where,$page,$num);
        if(!empty($list)){
            $list = $list->toArray();
            $count = Detailed::detailedCount($where);
            foreach($list as $k => $v){
                $list[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
        }else{
            $count = 0;
        }
        return [$list,$count];
    }




    /*** 银行卡截取后四位  支付宝手机号码隐藏中间四位   邮箱隐藏中间部分
     * @param $bankType
     * @param $bankCord
     * @return false|string|string[]
     */
    public static function bankCardEdit($bankType,$bankCord){
        if($bankType == 1){
            return substr($bankCord,-4);
        }else{
            return  self::alipayName($bankCord);
        }
    }




    //支付宝账号  根据手机号码或者邮箱 隐藏中间字段
    private static function alipayName($alipayName){
        if(strpos($alipayName,'@') !== false){ //为邮箱
            return substr($alipayName,0,3) .'****'. strstr($alipayName, '@');
        }else{ //为手机号码
            return substr_replace($alipayName,'****',3,4);
        }
    }

    //截取真实姓名
    private static function alipayUsername($alipayUsername){
        return mb_strcut($alipayUsername, 0, 3, 'utf-8') . '**';
    }

}